import React, { Component } from 'react';
import ThePagination from "@/components/ThePagination";
import { Modal, message } from "antd";
import { ExclamationCircleOutlined } from "@ant-design/icons";
import TheTable from "@/components/TheTable";
import TheButton from "@/components/TheButton";
import { apiGetstockPurchasePage, apiStockPurchaseDelet, apiStockPurchaseNoteOrderCancel } from "@/request/procurement"
import { apiStockTakeListAddBefore } from '@/request/storageManager/stock.js'
import { exportSheetTable } from '@/utils/exportTable.js';
import store from "@/store/store"
import TheQueryForm from '../../../components/TheQueryForm';
import TheTableExtend from '@/components/TheTableExtend'

export default class ProcurementList extends Component {
    constructor() {
        super()
        this.formRef_code = React.createRef()
        this.queryFormRef = React.createRef()
        this.state = {
            columns: [
                {
                    title: "序号",
                    dataIndex: "index",
                    key: "index",
                    render: (text, record, index) => {
                        return ((this.state.pageData.pageNo - 1) * (this.state.pageData.pageSize) + (index + 1));
                    }
                },
                {
                    title: "采购单号",
                    dataIndex: "code",
                    key: "code",
                    render: (text, render) => {
                        return text
                    }
                },
                {
                    title: "供应商",
                    dataIndex: "supplierName",
                    key: "supplierName",
                    render: (text, render) => {
                        return text
                    }
                },
                {
                    title: "仓库",
                    dataIndex: "libraryName",
                    key: "libraryName",
                    render: (text, render) => {
                        return text
                    }
                },
                {
                    title: "是否委外仓",
                    dataIndex: "isOutsource",
                    key: "isOutsource",
                    render: (text, render) => {
                        return text ? '否' : '是'
                    }
                },
                // {
                //     title: "商品总价值",
                //     dataIndex: "serviceShowFile",
                //     key: "serviceShowFile",
                //     render: (text, render) => {
                //         return text
                //     }
                // },
                {
                    title: "创建人",
                    dataIndex: "memberName",
                    key: "memberName",
                    render: (text, render) => {
                        return text
                    }
                },
                {
                    title: "创建时间",
                    dataIndex: "createTime",
                    key: "createTime",
                    render: (text, render) => {
                        return text
                    }
                },
                {
                    title: "订单状态",
                    dataIndex: "status",
                    key: "status",
                    render: (text, render) => {
                        let status = ""
                        switch (text) {
                            case 0:
                                status = <div style={{ color: "red" }} >未完成</div>
                                break;
                            case 1:
                                status = <div style={{ color: "orange" }} >处理中</div>
                                break;
                            case 2:
                                status = <div style={{ color: "green" }} >已完成</div>
                                break;

                            case 3:
                                status = <div style={{ color: "#999" }} >已关闭</div>
                                break;
                            default:
                                break;
                        }
                        return status
                    }
                },
                {
                    title: "操作",
                    dataIndex: "serviceShowFile",
                    key: "serviceShowFile",
                    render: (text, render) => {
                        return <div>
                            <TheButton haspermi={['procurement:list:detail']} onClick={() => this.props.history.push('/procurement/details/' + render.id)}>查看详情</TheButton>
                            {
                                render.isOutsource ? <TheButton haspermi={['procurement:list:delet']}
                                    onClick={() => this.deleteProcurementOrder(render.id, render.code)}
                                >删除</TheButton> : render.status == 1 && render.portionDelivery == 1 ? <TheButton haspermi={['procurement:list:delet']}
                                    onClick={() => this.closeOrder(render)}
                                >采购关单</TheButton> : null
                            }


                        </div>
                    }
                },
            ],
            dataSource: [],
            pageData: {
                pageNo: 1,
                pageSize: 10
            },
            total: 0,
            code: "",
            form_show: true,
            NewColumns: [],
            searchOption: [
                { field: 'goodsName', label: '物料名称', placeholder: '请输入', required: false, rules: [], type: 'Input', defaultValue: '' },
                { field: 'code', label: '采购单号', placeholder: '请输入', required: false, rules: [], type: 'Input', defaultValue: '' },
                { field: 'libraryId', label: '仓库', placeholder: '请选择', required: false, rules: [], type: 'Select', txt: 'name', value: 'id', options: [] },
                { field: 'supplierName', label: '供应商', placeholder: '请输入', required: false, rules: [], type: 'Input', defaultValue: '' },
                { field: 'skuNo', label: '物料ID', placeholder: '请输入', required: false, rules: [], type: 'Input', defaultValue: '' },
                { field: 'status', label: '订单状态', placeholder: '请选择', required: false, rules: [], type: 'Select', options: [{ label: "未完成", value: "0" }, { label: "处理中", value: "1" }, { label: "已完成", value: "2" }, { label: "已关闭", value: "3" }] },
            ],
            queryForm: {

            },
            selectedKeys: { 1: [] }
        }
    }
    componentDidMount() {
        this.onColumnsFilter(this.state.columns)
        this.getLibrarys()
        let searchParams = store.getState().searchValue
        let { pageNo, pageSize, queryForm,pathName } = searchParams
        if (searchParams && pageNo&&pathName=='procurement') {
            // let { pageNo, pageSize, searchValue } = searchParams
            this.setState({
                queryForm,
                pageData: {
                    pageNo: pageNo, pageSize: pageSize
                }
            }, () => {
                this.queryFormRef.onSetDefault({ ...queryForm })
                this.getData()
            })
        } else {
            this.getData()
        }

    }
    onColumnsFilter = (value) => {
        this.setState({
            NewColumns: value
        })
    }
    onTableRefresh() {
        this.getData()
    }
    onReset() {
        this.setState({
            queryForm: {},
            pageData: {
                pageNo: 1,
                pageSize: 10
            },
        }, () => {
            this.getData()
        })
    }
    async getLibrarys() {
        let res = await apiStockTakeListAddBefore()
        if (res.code === 0) {
            // console.log(res.data.librarys);
            this.state.searchOption[2].options = res.data.librarys
            this.setState({
                searchOption: this.state.searchOption
            })
        }
    }
    getData = (values) => {
        let { pageNo, pageSize } = this.state.pageData
        this.setState({
            queryForm: values === undefined ? this.state.queryForm : { ...values }
        }, async () => {
            const params = {
                pageNo, pageSize, queryForm: this.state.queryForm
            }
            store.dispatch({
                type: 'SaveSearchValues',
                data: {
                    pathName:'procurement',
                    ...params
                }
            })
            let res = await apiGetstockPurchasePage({
                pageNo, pageSize, ...this.state.queryForm
            })
            if (res.code === 0) {
                this.setState({
                    dataSource: res.data,
                    total: res.totalCount,
                })
            }
        })
    }
    // 采购关单
    closeOrder = (row) => {
        Modal.confirm({
            title: '提示',
            icon: <ExclamationCircleOutlined />,
            content: `采购关单后，同时将作废WMS的单据，该采购单将无法继续收货`,
            okText: '确认',
            cancelText: '取消',
            onOk: async () => {
                apiStockPurchaseNoteOrderCancel({ id: row.id }).then(res => {
                    if (res.code == 0) {
                        message.info("删除成功")
                        this.getData()
                    }
                })

            }
        })


    }
    setSearchValue = async (e) => {
        let status = e === undefined ? "" : e
        let { pageData, code } = this.state
        let params = {
            code, ...pageData,
            status
        }
        let res = await apiGetstockPurchasePage({
            ...params
        })
        if (res.code === 0) {
            this.setState({
                dataSource: res.data,
                total: res.totalCount,
            })
        }
    }
    deleteProcurementOrder = (id, code) => {
        Modal.confirm({
            title: '提示',
            icon: <ExclamationCircleOutlined />,
            content: `即将删除单号为：${code}采购单，删除后不可恢复，是否确定删除？`,
            okText: '确认',
            cancelText: '取消',
            onOk: async () => {
                let res = await apiStockPurchaseDelet({ id: id })
                if (res.code === 0) {
                    message.info("删除成功")
                    this.getData()
                }
            }
        })
    }
    pageChange = (pageNo, pageSize) => {
        this.setState({
            pageData: {
                pageNo, pageSize
            }
        }, () => {
            this.getData()
        })
    };
    onFormSearch(values) {
        this.setState({
            pageData: { pageNo: 1, pageSize: 10 }
        }, () => {
            this.getData(values)
        })
    }

    onChange = (selectedRowKeys, selectedRows) => {
        let pageNo = this.state.pageData.pageNo
        let selectedKeys = { ...this.state.selectedKeys }
        selectedKeys[pageNo] = selectedRowKeys
        this.setState({
            selectedKeys
        }, () => {
            console.log(this.state.selectedKeys);
        })
    }

    toExport = async () => {
        const { queryForm } = this.state
        let ids = ""
        Object.values(this.state.selectedKeys).forEach(value => {
            ids += value.toString() + ","
        })
        if (ids === ",") {
            ids = ""
        }
        await React.$post("/admin/stockPurchaseNote/getPurchaseNoteDetailListById", { ...queryForm, ids }).then(res => {
            if (res.code === 0 && res.data) {
                let th_arr = [
                    {
                        title: '采购单详情',
                        prop: '',
                        children: [
                            {
                                title: '序号',
                                prop: 'index'
                            },
                            {
                                title: '采购单号',
                                prop: 'code'
                            },
                            {
                                title: '供应商',
                                prop: 'supplierName'
                            },
                            {
                                title: '仓库',
                                prop: 'libraryName'
                            },
                            {
                                title: '创建人',
                                prop: 'createUserName'
                            },
                            {
                                title: '创建时间',
                                prop: 'createTime'
                            },
                            {
                                title: '订单状态',
                                prop: 'status'
                            },
                            {
                                title: '物品名称',
                                prop: 'materialName',
                            },
                            {
                                title: "物料ID",
                                prop: "materialId",
                            },
                            {
                                title: '规格',
                                prop: 'skuName',
                            },
                            {
                                title: '含税单价',
                                prop: 'taxPrice',
                                valueType: 'number'
                            },
                            {
                                title: '含税总价',
                                prop: 'taxNumPrice',
                                valueType: 'number'
                            },
                            {
                                title: '应收数量',
                                prop: 'shouldInNum',
                                valueType: 'number'
                            },
                            {
                                title: '实收数量',
                                prop: 'realInNum',
                                valueType: 'number'
                            },
                        ]
                    },
                ]
                let tb_arr = []
                res.data.forEach((item, index) => {
                    let status = ""
                    switch (item.status) {
                        case 0:
                            status = "未完成"
                            break;
                        case 1:
                            status = "处理中"
                            break;
                        case 2:
                            status = "已完成"
                            break;
                        default:
                            break;
                    }
                    item.stockPurchaseNoteDetailVos.forEach(item2 => {
                        tb_arr.push({
                            index: item.noteIndex,
                            code: item.code || '/',
                            supplierName: item.supplierName || '/',
                            libraryName: item.libraryName || '/',
                            createUserName: item.createUserName || '/',
                            createTime: item.createTime || '/',
                            status: status || '/',
                            materialName: item2.materialName || '/',
                            materialId: item2.materialId || '/',
                            skuName: item2.skuName || '/',
                            taxPrice: (item2.taxPrice / 100).toFixed(2) || '/',
                            taxNumPrice: (item2.taxNumPrice / 100).toFixed(2) || '/',
                            shouldInNum: item2.shouldInNum || '/',
                            realInNum: item2.realInNum || '/',
                        })
                    })
                })
                const mergeProp = [
                    'index',
                    'code',
                    'supplierName',
                    'libraryName',
                    'status',
                    'createTime',
                    'createUserName',
                ]
                exportSheetTable({ fileName: '采购单详情', tH_data: th_arr, tB_data: tb_arr, isSheet: true, merge: true, mergeProp })
                this.setState({
                    selectedKeys: { 1: [] }
                })
            }
        })
    }

    render() {
        let { columns, dataSource, pageData, total, NewColumns, form_show, searchOption, selectedKeys } = this.state
        const rowSelection = {
            selectedRowKeys: selectedKeys[pageData.pageNo],
            onChange: this.onChange,
        }
        return (
            <div className="p-layout-box commodity-examine">
                <TheQueryForm ref={(ref) => this.queryFormRef = ref} show={form_show} option={searchOption} onGetValues={(values) => this.onFormSearch(values)} onReset={() => { this.onReset() }}>
                </TheQueryForm>
                <TheTableExtend
                    columns={columns}
                    onFormTrigger={() => this.setState({ form_show: !this.state.form_show })}
                    onTableRefresh={() => this.onTableRefresh()}
                    onColumnsFilter={(value) => { this.onColumnsFilter(value) }}
                >
                    <TheButton haspermi={['procurement:List:create']} size="middle" onClick={() => this.props.history.push('/procurement/add')} type="primary">创建</TheButton>
                    <TheButton size="middle" onClick={() => this.toExport()} type="default">导出</TheButton>
                </TheTableExtend>


                <TheTable
                    scroll={{ x: "max-content", y: '63vh' }}
                    columns={NewColumns}
                    dataSource={dataSource}
                    rowKey={record => record.id}
                    rowSelection={rowSelection}
                />
                <ThePagination
                    pageNo={pageData.pageNo}
                    pageSize={pageData.pageSize}
                    total={total}
                    pageChange={this.pageChange}
                />
            </div>
        );
    }
}
